package cn.jbolt.ai.core.chain.source;

import cn.jbolt.ai.app.vo.ActionData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求来源渠道
 */
public class SourceChannel {
    private static final Logger logger = LoggerFactory.getLogger(SourceChannel.class);
    private SourceType sourceType;

    private WebSocketSession session;

    private HttpServletRequest request;

    private SourceChannel(){}



    public static SourceChannel from(HttpServletRequest request) {
        SourceChannel channel = new SourceChannel();
        channel.sourceType = SourceType.HTTP;
        channel.request = request;
        return channel;
    }

    public static SourceChannel from(WebSocketSession session) {
        SourceChannel channel = new SourceChannel();
        channel.sourceType = SourceType.WEBSOCKET;
        channel.session = session;
        return channel;
    }

    /**
     * 发送websocket数据
     * @param data
     */
    public void sendSocketData(ActionData data) {
        if (sourceType == SourceType.WEBSOCKET) {
            try {
                this.session.sendMessage(new TextMessage(data.toString()));
            } catch (IOException e) {
                logger.error("发送websocket数据异常", e);
                throw new RuntimeException(e);
            }
        }
    }


    public SourceType getSourceType() {
        return sourceType;
    }


    public WebSocketSession getSession() {
        return session;
    }


    public HttpServletRequest getRequest() {
        return request;
    }

}
